import 'package:dio/dio.dart';
import 'package:myapp/http/core/adapter/net_adapter.dart';
import 'package:myapp/http/core/base_request.dart';
import 'package:myapp/http/core/net_response.dart';

class DioAdapter extends AbsNetAdapter {
  late final Dio _mDioClinet;

  DioAdapter() {
    _mDioClinet = Dio();
    _mDioClinet.interceptors.add(LogInterceptor(
        requestBody: true, // 记录请求体
        responseBody: true));
  }

  @override
  Future<CoreResponse> send(String baseUrl, BaseRequest request) async {
    Response? response;

    var option = Options(headers: request.getHeaders());

    // DioException? error;

    // try {
    if (request.httpMethod() == HttpMethod.GET) {
      response =
          await _mDioClinet.get(baseUrl + request.url(), options: option);
    } else if (request.httpMethod() == HttpMethod.POST) {
      response = await _mDioClinet.post(baseUrl + request.url(),
          options: option, data: request.getRequestBody());
    } else {
      assert(false, "not support");
    }
    // } on DioException catch (e) {
    //   error = e;
    //   response = e.response;
    // }
    //
    // if (error != null) {
    //   throw NetError(response?.statusCode ?? -9999, error.toString(),
    //       data: await buildResponse(request, response));
    // }

    return buildResponse(request, response);
  }

  Future<CoreResponse> buildResponse(
      BaseRequest request, Response? response) {
    return Future.value(CoreResponse(request, response?.statusCode,
        response?.statusMessage, response?.data));
  }
}
